{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div align=\"right\"><i>Peter Norvig</i></div>\n",
    "\n",
    "# The Devil and the Coin Flip Game\n",
    "\n",
    "If the Devil ever challenges me to a [fiddle contest](https://en.wikipedia.org/wiki/The_Devil_Went_Down_to_Georgia), I'm going down. But here is a contest where I'd have a better chance:\n",
    "\n",
    "> *You're playing a game with the Devil, with your soul at stake. You're sitting at a circular table which has 4 coins, arranged in a diamond, at the 12, 3, 6, and 9 o'clock positions. You are blindfolded, and can never see the coins or the table.*\n",
    "\n",
    "> *Your goal is to get all 4 coins showing heads, by telling the devil the position(s) of some coins to flip. We call this a \"move\" on your part. The Devil must faithfully perform the requested flips, but may first sneakily rotate the table any number of quarter-turns, so that the coins are in different positions. You keep making moves, and the Devil keeps rotating and flipping, until all 4 coins show heads.*\n",
    "\n",
    "> *Example: You tell the Devil to flip the 12 o'clock and 6 o'clock positions. The devil might rotate the table a quarter turn clockwiae, and then flip the coins that have moved into the 12 o'clock and 6 o'clock positions (which were formerly at 3 o'clock and 9 o'clock).  Or the Devil could have made any other rotation before flipping.*\n",
    "\n",
    "> *What is a shortest sequence of moves that is **guaranteed** to win, no matter what the initial state of the coins, and no matter what rotations the Devil applies?*\n",
    "\n",
    "(This same puzzle also appeared in [The Riddler on 21 June 2019](https://fivethirtyeight.com/features/i-would-walk-500-miles-and-i-would-riddle-500-more/), with the role of the devil played by a banker. I'm not sure which is scarier.)\n",
    "\n",
    "# Analysis\n",
    "\n",
    "- We're looking for a \"shortest sequence of moves\" that reaches a goal. That's a [shortest path search problem](https://en.wikipedia.org/wiki/Shortest_path_problem). I've done that before.\n",
    "- Since the Devil gets to make moves too, you might think that this is a [minimax](https://en.wikipedia.org/wiki/Minimax) problem: that we should choose the move that leads to the shortest path, given that the Devil has the option of making moves that lead to the longest path.\n",
    "- But minimax only works when you know what moves the opponent is making: he did *that*, so I'll do *this*. In this problem the player is blinfolded; that makes it a [partially observable problem](https://en.wikipedia.org/wiki/Partially_observable_system) (in this case, not observable at all, but it is traditional to say \"partially\").\n",
    "- In such problems, we don't know for sure the true state of the world before or after any move. So we should represent what *is* known: *the set of states that we believe to be possible*. We call this a *belief state*. At the start of the game, each of the four coins could be either heads or tails, so that's 2<sup>4</sup> = 16 possibilities in the initial belief state:\n",
    "       {HHHH, HHHT, HHTH, HHTT, HTHH, HTHT, HTTH, HTTT, \n",
    "        THHH, THHT, THTH, THTT, TTHH, TTHT, TTTH, TTTT}\n",
    "- So we have a single-agent shortest-path search in the space of belief states (not the space of physical states of the coins). We search for a path from the inital belief state to the goal belief state, which is `{HHHH}` (meaning that 4 heads is the only possibility).\n",
    "- A move updates the belief state as follows: for every four-coin sequence in the current belief state, rotate it in every possible way, and then flip the coins specified by the position(s) in the move. Collect all these results together to form the new belief state. The search space is small (just 2<sup>16</sup> possible belief states), so run time will be fast. \n",
    "- I'll [Keep It Simple](https://en.wikipedia.org/wiki/KISS_principle), and not worry about rotational symmetry  (although we'll come back to that later).\n",
    "\n",
    "\n",
    "# Basic Data Structures and Functions\n",
    "\n",
    "What data structures will I be dealing with?\n",
    "\n",
    "\n",
    "\n",
    "- `Coins`: a *coin sequence* (four coins, in order, on the table) is represented as a `str` of four characters, such as `'HTTT'`. \n",
    "- `Belief`: a *belief state* is a `frozenset` of `Coins` (frozen so it can be hashed), like `{'HHHT', 'TTTH'}`.\n",
    "- `Position`: an integer index into the coin sequence; position `0` selects the `H` in `'HTTT'`.\n",
    "- `Move`: a set of positions to flip, such as `{0, 2}`. \n",
    "- `Strategy`: an ordered list of moves. A\n",
    "blindfolded player has no feedback, thus there are no  decision points in the strategy. \n",
    "\n",
    "I take the coin sequence `'HTTT'` to mean there is an `'H'` at the 12 o'clock position, then 3, , 6, and 9 o'clock in that order are `'T'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "from itertools   import product, combinations, chain\n",
    "import random\n",
    "\n",
    "Coins     = ''.join   # A coin sequence; a str: 'HHHT'.\n",
    "Belief    = frozenset # A set of possible coin sequences: {'HHHT', 'TTTH'}.\n",
    "Position  = int       # An index into a coin sequence.\n",
    "Move      = set       # A set of positions to flip: {0, 2}\n",
    "Strategy  = tuple     # A sequence of Moves: ({0, 1, 2, 3}, {0, 2}, ...)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What basic functions do I need to manipulate these data structures?\n",
    "\n",
    "- `all_moves()`: returns a list of every possible move a player can make.\n",
    "- `all_coins()`: returns a belief state consisting of the set of all 16 possible coin sequences: `{'HHHH', 'HHHT', ...}`.\n",
    "- `rotations(coins)`: returns a belief set of all 4 rotations of the coin sequence.\n",
    "- `flip(coins, move)`: flips the specified positions within the coin sequence.\n",
    " (But leave `'HHHH'` alone, because it ends the game.)\n",
    "- `update(belief, move)`: returns an updated belief state: all the coin sequences that could result from any rotation followed by the specified flips.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def all_moves() -> (Move,): \n",
    "    \"List of all possible moves.\"\n",
    "    return tuple(map(Move, powerset(range(4))))\n",
    "\n",
    "def all_coins() -> Belief:\n",
    "    \"The belief set consisting of all possible coin sequences.\"\n",
    "    return Belief(map(Coins, product('HT', repeat=4)))\n",
    "\n",
    "def rotations(coins) -> {Coins}: \n",
    "    \"A set of all possible rotations of a coin sequence.\"\n",
    "    return {coins[r:] + coins[:r] for r in range(4)}\n",
    "\n",
    "def flip(coins, move) -> Coins:\n",
    "    \"Flip the coins in the positions specified by the move (but leave 'HHHH' alone).\"\n",
    "    if 'T' not in coins: return coins # Don't flip 'HHHH'\n",
    "    coins = list(coins) # Need a mutable sequence\n",
    "    for i in move:\n",
    "        coins[i] = ('H' if coins[i] == 'T' else 'T')\n",
    "    return Coins(coins)\n",
    "\n",
    "def update(belief, move) -> Belief:\n",
    "    \"Update belief: consider all possible rotations, then flip.\"\n",
    "    return Belief(flip(c, move)\n",
    "                  for coins in belief\n",
    "                  for c in rotations(coins))\n",
    "\n",
    "flatten = chain.from_iterable\n",
    "\n",
    "def powerset(iterable): \n",
    "    \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n",
    "    # https://docs.python.org/3/library/itertools.html#itertools-recipes\n",
    "    s = list(iterable)\n",
    "    return flatten(combinations(s, r) for r in range(len(s) + 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try out these functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(set(),\n",
       " {0},\n",
       " {1},\n",
       " {2},\n",
       " {3},\n",
       " {0, 1},\n",
       " {0, 2},\n",
       " {0, 3},\n",
       " {1, 2},\n",
       " {1, 3},\n",
       " {2, 3},\n",
       " {0, 1, 2},\n",
       " {0, 1, 3},\n",
       " {0, 2, 3},\n",
       " {1, 2, 3},\n",
       " {0, 1, 2, 3})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_moves()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "frozenset({'HHHH',\n",
       "           'HHHT',\n",
       "           'HHTH',\n",
       "           'HHTT',\n",
       "           'HTHH',\n",
       "           'HTHT',\n",
       "           'HTTH',\n",
       "           'HTTT',\n",
       "           'THHH',\n",
       "           'THHT',\n",
       "           'THTH',\n",
       "           'THTT',\n",
       "           'TTHH',\n",
       "           'TTHT',\n",
       "           'TTTH',\n",
       "           'TTTT'})"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_coins()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'HHHT', 'HHTH', 'HTHH', 'THHH'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rotations('HHHT')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'THTT'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "flip('HHHT', {0, 2})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are 16 coin sequences in the `all_coins` belief state. If we update this belief state by flipping all 4 positions, we should get a new belief state where we have eliminated the possibility of 4 tails (because if there had been 4 heads, you would have already won), leaving 15 possible coin sequences:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "frozenset({'HHHH',\n",
       "           'HHHT',\n",
       "           'HHTH',\n",
       "           'HHTT',\n",
       "           'HTHH',\n",
       "           'HTHT',\n",
       "           'HTTH',\n",
       "           'HTTT',\n",
       "           'THHH',\n",
       "           'THHT',\n",
       "           'THTH',\n",
       "           'THTT',\n",
       "           'TTHH',\n",
       "           'TTHT',\n",
       "           'TTTH'})"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "update(all_coins(), {0, 1, 2, 3})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(powerset([1,2,3]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Everything looks good so far. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Search for a Winning Strategy\n",
    "\n",
    "The generic function `search` does a breadth-first search starting\n",
    "from a `start` state, looking for a `goal`  state, considering possible `actions` at each turn,\n",
    "and computing the `result` of each action (`result` is a function such that `result(state, action)` returns the new state that results from executing the action in the current state). `search` works by keeping a `queue` of unexplored possibilities, where each entry in the queue is a pair consisting of a *strategy* (sequence of moves) and a *state* that that strategy leads to. We also keep track of a set of `explored` states, so that we don't repeat ourselves. I've defined this function (or one just like it) multiple times before, for use in different search problems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def search(start, goal, actions, result) -> Strategy:\n",
    "    \"Breadth-first search from start state to goal; return strategy to get to goal.\"\n",
    "    explored = set()\n",
    "    queue = deque([(Strategy(), start)])\n",
    "    while queue: # Entries in queue are (move_sequence, end_state) pairs\n",
    "        (strategy, state) = queue.popleft()\n",
    "        if state == goal:\n",
    "            return strategy\n",
    "        for action in actions:\n",
    "            state2 = result(state, action)\n",
    "            if state2 not in explored:\n",
    "                queue.append((strategy + (action,), state2))\n",
    "                explored.add(state2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that `search` doesn't know anything about belief states&mdash;it is designed to work on plain-old physical states of the world. But amazingly, we can still use it to search over belief states: it just works, as long as we properly specify the start state, the goal state, and the means of moving between states.\n",
    "\n",
    "The `coin_search` function calls  `search` to solve our specific problem:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3})"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def coin_search() -> Strategy: \n",
    "    \"Use `search` to solve the Coin Flip problem.\"\n",
    "    return search(start=all_coins(), goal={'HHHH'}, actions=all_moves(), result=update)\n",
    "\n",
    "coin_search()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's a 15-move strategy that is guaranteed to lead to a win. **Stop  here** if all you want is the answer to the puzzle. \n",
    "\n",
    "----\n",
    "\n",
    "Or you can continue on ...\n",
    "\n",
    "# Verifying the Winning Strategy\n",
    "\n",
    "I don't have a proof, but I have some evidence that this strategy is the answer:\n",
    "- Exploring with paper and pencil, it looks good. \n",
    "- A colleague did the puzzle and got the same answer. \n",
    "- It passes the `probably_wins` test below.\n",
    "\n",
    "The call `probably_wins(strategy, k)` plays the strategy *&nbsp;k* times against each possible starting position, assuming a Devil that chooses rotations at random. Note this is dealing with concrete, individual states of the world, like `HTHH`, not belief states. If `probably_wins` returns `False`, then the strategy is *definitely* flawed. If it returns `True`, then the strategy is *probably* good, but that does not prove it will win every time (and either way `probably_wins` makes no claims about being a *shortest* strategy)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def probably_wins(strategy, k=100) -> bool:\n",
    "    \"Is this a winning strategy? A probabilistic algorithm.\"\n",
    "    return all('T' not in play(strategy, coins)\n",
    "               for coins in all_coins() \n",
    "               for _ in range(k))\n",
    "\n",
    "def play(strategy, coins) -> Coins:\n",
    "    \"Play strategy for one game against a random Devil, starting with coins; return final state of coins.\"\n",
    "    for move in strategy:\n",
    "        if 'T' not in coins: return coins\n",
    "        coins = random.choice(list(rotations(coins)))\n",
    "        coins = flip(coins, move)\n",
    "    return coins\n",
    "\n",
    "probably_wins(strategy=coin_search())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Canonical Coin Sequences and Moves\n",
    "\n",
    "Consider these coin sequences: `{'HHHT', 'HHTH', 'HTHH', 'THHH'}`. In a sense, these are all the same: they all denote the same sequence of coins with the table rotated to different degrees. Since the devil is free to rotate the table any amount at any time, we could be justified in treating all four of these as equivalent, and collapsing them into one representative member. I will **redefine** `Coins` so that is still takes an iterable of `'H'` or `'T'` characters and joins them into a `str`, but I will make it consider all possible rotations of the resulting string and (arbitraily) choose the one that comes first in alphabetical order (which would be `'HHHT'` for the four coin sequences mentioned here)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Coins(coins) -> str: \n",
    "    \"The canonical representation (after rotation) of the 'H'/'T' sequence.\"\n",
    "    return min(rotations(''.join(coins)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert Coins('HHHT') == Coins('HHTH') == Coins('HTHH') == Coins('THHH') == 'HHHT'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `Coins` redefined, the result of `all_coins()` is different:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "frozenset({'HHHH', 'HHHT', 'HHTT', 'HTHT', 'HTTT', 'TTTT'})"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_coins()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The starting belief set is down from 16  to 6, namely:  {4 heads, 3 heads, 2 adjacent heads, 2 opposite heads, 1 head, and no heads}, respectively. \n",
    "\n",
    "Now for canonical moves. The moves `{0}` and `{1}` should be considered the same, since they both say \"flip one coin.\" To get that, look at the canonicalized set of `all_coins(N)`, and for each one pull out  the set of positions that have an `H` in them and flip those positions. (The positions with a `T` should be symmetric, so we don't need them as well.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def all_moves() -> [Move]:\n",
    "    \"All canonical moves.\"\n",
    "    return [Move(i for i in range(4) if coins[i] == 'H')\n",
    "            for coins in sorted(all_coins())]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{0, 1, 2, 3}, {0, 1, 2}, {0, 1}, {0, 2}, {0}, set()]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_moves()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So again we've gone down from 16 to 6.\n",
    "\n",
    "Let's make sure we didn't break anything and that we still get the same 15-step solution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3})"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coin_search()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Winning Strategies for N Coins\n",
    "\n",
    "What if there are 3 coins on the table arranged in a triangle? Or 6 coins in a hexagon? To answer that, I'll generalize all the functions that have a \"4\" in them: `all_moves, all_coins`, `rotations` and `coin_search`, as well as `probably_wins`. In each case the chage is trivial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def all_moves(N=4) -> [Move]:\n",
    "    \"All canonical moves for a sequence of N coins.\"\n",
    "    return [Move(i for i in range(N) if coins[i] == 'H')\n",
    "            for coins in sorted(all_coins(N))]\n",
    "\n",
    "def all_coins(N=4) -> Belief:\n",
    "    \"Return the belief set consisting of all possible coin sequences.\"\n",
    "    return Belief(map(Coins, product('HT', repeat=N)))\n",
    "\n",
    "def rotations(coins) -> {Coins}: \n",
    "    \"A list of all possible rotations of a coin sequence.\"\n",
    "    return {coins[r:] + coins[:r] for r in range(len(coins))}\n",
    "\n",
    "def coin_search(N=4) -> Strategy: \n",
    "    \"Use the generic `search` function to solve the Coin Flip problem.\"\n",
    "    return search(start=all_coins(N), goal={'H' * N}, actions=all_moves(N), result=update)\n",
    "\n",
    "def probably_wins(strategy, N=4, k=1000) -> bool:\n",
    "    \"Is this a winning strategy? A probabilistic algorithm.\"\n",
    "    return all('T' not in play(strategy, coins)\n",
    "               for coins in all_coins(N) \n",
    "               for _ in range(k))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's test the new definitions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert all_moves(3) == [{0, 1, 2}, {0, 1}, {0}, set()]\n",
    "assert all_moves(4) == [{0, 1, 2, 3}, {0, 1, 2}, {0, 1}, {0, 2}, {0}, set()]\n",
    "\n",
    "assert all_coins(4) == {'HHHH', 'HHHT', 'HHTT', 'HTHT', 'HTTT', 'TTTT'}\n",
    "assert all_coins(5) == {'HHHHH','HHHHT', 'HHHTT','HHTHT','HHTTT', 'HTHTT', 'HTTTT', 'TTTTT'}\n",
    "\n",
    "assert rotations('HHHHHT') == {'HHHHHT', 'HHHHTH', 'HHHTHH', 'HHTHHH', 'HTHHHH', 'THHHHH'}\n",
    "assert update({'TTTTTTT'}, {3}) == {'HTTTTTT'}\n",
    "assert (update(rotations('HHHHHT'), {0}) == update({'HHTHHH'}, {1}) == update({'THHHHH'}, {2})\n",
    "        == {'HHHHHH', 'HHHHTT', 'HHHTHT', 'HHTHHT'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3},\n",
       " {0, 1},\n",
       " {0, 1, 2, 3},\n",
       " {0, 2},\n",
       " {0, 1, 2, 3})"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coin_search(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How many distinct canonical coin sequences are there for up to a dozen coins?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1: 2,\n",
       " 2: 3,\n",
       " 3: 4,\n",
       " 4: 6,\n",
       " 5: 8,\n",
       " 6: 14,\n",
       " 7: 20,\n",
       " 8: 36,\n",
       " 9: 60,\n",
       " 10: 108,\n",
       " 11: 188,\n",
       " 12: 352}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "{N: len(all_coins(N))\n",
    " for N in range(1, 13)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On the one hand this is encouraging; there are only 352 canonical coin sequences of length 12, far less than the 4,096 non-canonical squences. On the other hand, it is discouraging; since we are searching over belief states, that would be 2<sup>352</sup> belief states, which is more than a googol. However, we should be able to easily handle up to N=7, because 2<sup>20</sup> is only a million.\n",
    "\n",
    "# Winning Strategies for N = 1 to 7 Coins"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1: ({0},),\n",
       " 2: ({0, 1}, {0}, {0, 1}),\n",
       " 3: None,\n",
       " 4: ({0, 1, 2, 3},\n",
       "  {0, 2},\n",
       "  {0, 1, 2, 3},\n",
       "  {0, 1},\n",
       "  {0, 1, 2, 3},\n",
       "  {0, 2},\n",
       "  {0, 1, 2, 3},\n",
       "  {0, 1, 2},\n",
       "  {0, 1, 2, 3},\n",
       "  {0, 2},\n",
       "  {0, 1, 2, 3},\n",
       "  {0, 1},\n",
       "  {0, 1, 2, 3},\n",
       "  {0, 2},\n",
       "  {0, 1, 2, 3}),\n",
       " 5: None,\n",
       " 6: None,\n",
       " 7: None}"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "{N: coin_search(N) for N in range(1, 8)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Too bad; there are no winning strategies for N = 3, 5, 6, or 7.  \n",
    "\n",
    "There *are* winning strategies for N = 1, 2, 4; they have lengths 1, 3, 15, respectively. Hmmm. That suggests ...\n",
    "\n",
    "# A Conjecture\n",
    "\n",
    "- For every N that is a power of 2, there will be a shortest winning strategy of length 2<sup>N</sup> - 1.\n",
    "- For every N that is not a power of 2, there will be no winning strategy. \n",
    "\n",
    "# Winning Strategy for 8 Coins\n",
    "\n",
    "For N = 8, there are 2<sup>36</sup> = 69 billion belief states and if the conjecture is true there will be a shortest winning strategy with 255 steps. All the computations up to now have been less than a second, but this one should take more than a minute. Let's see:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min 11s, sys: 122 ms, total: 1min 11s\n",
      "Wall time: 1min 11s\n"
     ]
    }
   ],
   "source": [
    "%time strategy8 = coin_search(8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "probably_wins(strategy8, N=8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "255"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(strategy8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Eureka!** That's evidence in favor of the conjecture. But not proof. And it leaves many questions unanswered:\n",
    "- Can you show there are no winning strategies for *N* = 9? Currently, `coin_search(9)` should take about 20 million minutes.\n",
    "- Can you show there are no winning strategies for *N* = 10, 11, ...?\n",
    "- Can you prove there are no winning strategies for any *N* that is not a power of 2?\n",
    "- Can you find a winning strategy of length 65,535 for *N* = 16 and verify that it works?\n",
    "- Can you generate a winning strategy for any power of 2 (without proving it is shortest)?\n",
    "- Can you prove there are no shorter winning strategies for *N* = 16?\n",
    "- Can you prove the conjecture in general?\n",
    "- Can you *understand* and *explain* how the strategy works, rather than just listing the moves?\n",
    "\n",
    "# A Proof of the Conjecture (from John Lamping)\n",
    "\n",
    "John Lamping came up with this proof of the conjecture:\n",
    "\n",
    "First, consider n = 3. If the three coins start out different, the devil can guarantee that they are still different after any flip you call for. If you ask for 1 flip, the devil makes the flip apply to one of the two matching coins. If you ask for 2 flips, the devil makes the flip apply to a pair of non-matching coins. If you ask for all 3 flips, they will still disagree, as well. So there is no strategy for 3 coins.\n",
    "\n",
    "We can generalize this to any prime number of coins, p, different from 2. If the p coins start out different, the devil can still make sure that any flip will leave the coins not matching. If the flip is of all coins, they will still disagree. Suppose it is not of all coins. The devil tries the flip on the current orientation of the table. If that leaves coins different, good. If not, the devil rotates the table by one position. We show that in that position, the coins will disagree after the flip. We know that there are at least two coins that the player asked to be flipped differently. With an odd number of coins, (LFFLF, for example) we also know there must be two adjacent coins that the player asked to be flipped the same. So there must be a subsequence that is either LFF or FLL. We know that the coins initially agreed on the last two positions, because the flip led to all the coins matching. After the rotation, those two positions will be flipped differently, leading to different coins.\n",
    "\n",
    "Now, consider any multiple of p (say 12, for example, 3 × 4). We can pick out p equally spaced points on the table (every 4th coin in the example), and apply the devil's strategy for p coins to those p coins: If those p start out different, the devil can always make sure they stay different.\n",
    "\n",
    "So for any number of coins that has a factor other than 2, the devil wins.\n",
    "\n",
    "Now we have to show that for any number that is a power of 2, the devil loses.\n",
    "We proceed by induction. Suppose that we have a sequence of flip operations that guarantees a win for $2^n$ coins. We assume that there are $2^n - 1$ of them, $o_1, ... o_{2^n-1}$. Each operation specifies, for each of the n coins, whether to flip it or to leave alone, like LFFF. We create two new sequences, also of $2^n-1$ operations, but operating on $2^{n+1}$ coins. The first, called $d$ for double, does $o$ on the first $2^n$ coins, and then repeats the same pattern on the second $2^n$ coins. So if $o_i$ is LFFF, $d_i$ is LFFFLFFF. The second, for single, does $o$ on the first $2^n$ coins, and leaves the second $2^n$ coins alone. So if $o_i$ is LFFF, $s_i$ is LFFFLLLL. Then the following sequence of operations guarantees a win on $2^(n+1)$ coins: \n",
    "\n",
    "   $d_1, ... d_{2^n-1}, s_1, d_1, ... d_{2^n-1}, s_2, .... d_1, ... d_{2^n-1}, s_{2^n-1}, d_1, ... d_{2^n-1}$\n",
    "   \n",
    "That is, we do each operation of $s$, with a complete copy of $d$ between each $s$ operation, as well as at the beginning and at the end. The total number of operations is $2^n×(2^n - 1) + 2^n - 1 = 2^{n+1} -1.$\n",
    "\n",
    "Before explaining why this works, lets use it to generate the sequences we know. \n",
    "For one coin, we win with a sequence of a single operation, F. \n",
    "For two coins, d is the single operation FF, while s is the single operation FL. Combining them according to the procedure gives FF, FL, FF.\n",
    "For four coins, d is FFFF, FLFL, FFFF, while s is FFLL, FLLL, FFLL, combining them gives FFFF, FLFL, FFFF, FFLL, FFFF, FLFL, FFFF, FLLL, FFFF, FLFL, FFFF, FFLL, FFFF, FLFL, FFFF. That is the answer that we all came up with.\n",
    "\n",
    "To see why it works, consider all pairs of opposite coins on the table with $2^{n+1}$ coins, and consider the XOR of each pair of opposite coins. There are $2^n$ of these XORs, and there is a natural correspondence between each XOR pair and a single coin in the original game. Now, s complements the XOR of a pair exactly when o flips the corresponding coin in the original game. Meanwhile, every operation in d leaves the XOR of each pair unchanged. So, since the sequence of o operations explores all coins positions, the sequence of s operations explores all XOR states. And the interposed d operations don't interfere with that exploration. In one of those states, the XORs will all be 0, meaning that each pair of opposite coins will agree. But in that state, when opposite pairs of coins agree, d is equivalent to o, just operating on pairs of coins, rather than single coins. So it explores all possible combinations of heads and tails, given that opposites agree. That will include the state where all coins are heads.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualizing Strategies\n",
    "\n",
    "Can I understand what is going on by showing how belief states are whittled down?\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show(moves, N=4):\n",
    "    \"For each move, print the move number, move, and belief state.\"\n",
    "    belief = all_coins(N)\n",
    "    order = sorted(belief)\n",
    "    print('Move| Flips    | Belief State')\n",
    "    print('----+----------+-------------')\n",
    "    def show(i, move, order=sorted(belief)):\n",
    "        print(f'{i:3} | {movestr(move, N):8} | {beliefstr(belief, order)}')\n",
    "    show(0, set())\n",
    "    for (i, move) in enumerate(moves, 1):\n",
    "        belief = update(belief, move)\n",
    "        show(i, move)\n",
    "\n",
    "def beliefstr(belief, order) -> str: \n",
    "    return join(((coins if coins in belief else ' ' * len(coins))\n",
    "                 for coins in order), ' ')\n",
    "\n",
    "def movestr(move, N) -> str: \n",
    "    return join((i if i in move else ' ') \n",
    "                for i in range(N))\n",
    "    \n",
    "def join(items, sep='') -> str: \n",
    "    return sep.join(map(str, items))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following tables shows how moves change the belief state:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Move| Flips    | Belief State\n",
      "----+----------+-------------\n",
      "  0 |          | HH HT TT\n",
      "  1 | 01       | HH HT   \n",
      "  2 | 0        | HH    TT\n",
      "  3 | 01       | HH      \n"
     ]
    }
   ],
   "source": [
    "show(coin_search(2), 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Move| Flips    | Belief State\n",
      "----+----------+-------------\n",
      "  0 |          | HHHH HHHT HHTT HTHT HTTT TTTT\n",
      "  1 | 0123     | HHHH HHHT HHTT HTHT HTTT     \n",
      "  2 | 0 2      | HHHH HHHT HHTT      HTTT TTTT\n",
      "  3 | 0123     | HHHH HHHT HHTT      HTTT     \n",
      "  4 | 01       | HHHH HHHT      HTHT HTTT TTTT\n",
      "  5 | 0123     | HHHH HHHT      HTHT HTTT     \n",
      "  6 | 0 2      | HHHH HHHT           HTTT TTTT\n",
      "  7 | 0123     | HHHH HHHT           HTTT     \n",
      "  8 | 012      | HHHH      HHTT HTHT      TTTT\n",
      "  9 | 0123     | HHHH      HHTT HTHT          \n",
      " 10 | 0 2      | HHHH      HHTT           TTTT\n",
      " 11 | 0123     | HHHH      HHTT               \n",
      " 12 | 01       | HHHH           HTHT      TTTT\n",
      " 13 | 0123     | HHHH           HTHT          \n",
      " 14 | 0 2      | HHHH                     TTTT\n",
      " 15 | 0123     | HHHH                         \n"
     ]
    }
   ],
   "source": [
    "show(coin_search(4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that every odd-numbered move flips all four coins to eliminate the possibility of `TTTT`, flipping it to `HHHH`. We can also see that moves 2, 4, and 6 flip two coins and have the effect of eventually eliminating the two \"two heads\" sequences from the belief state, and then move 8 eliminates the \"three heads\" and \"one heads\" sequences, while bringing back the \"two heads\" possibilities. Repeating moves 2, 4, and 6 in moves 10, 12, and 14 then re-eliminates the \"two heads\", and move 15 gets the belief state down to `{'HHHH'}`.\n",
    "\n",
    "You could call `show(strategy, 8)`, but the results look bad unless you have a very wide (345 characters) screen to view it on. So instead I'll add a `verbose` parameter to `play` and play out some games with a trace of each move:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   1: HHTH | rot: THHH | flip: 0123 HTTT\n",
      "   2: HTTT | rot: THTT | flip: 0 2  HHHT\n",
      "   3: HHHT | rot: THHH | flip: 0123 HTTT\n",
      "   4: HTTT | rot: THTT | flip: 01   HTTT\n",
      "   5: HTTT | rot: THTT | flip: 0123 HHHT\n",
      "   6: HHHT | rot: HHHT | flip: 0 2  HTTT\n",
      "   7: HTTT | rot: THTT | flip: 0123 HHHT\n",
      "   8: HHHT | rot: THHH | flip: 012  HHTT\n",
      "   9: HHTT | rot: TTHH | flip: 0123 HHTT\n",
      "  10: HHTT | rot: HTTH | flip: 0 2  HHTT\n",
      "  11: HHTT | rot: TTHH | flip: 0123 HHTT\n",
      "  12: HHTT | rot: THHT | flip: 01   HTHT\n",
      "  13: HTHT | rot: HTHT | flip: 0123 HTHT\n",
      "  14: HTHT | rot: THTH | flip: 0 2  HHHH\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'HHHH'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def play(strategy, coins, verbose=False):\n",
    "    \"Play strategy for one game against a random Devil, starting with coins; return final state of coins.\"\n",
    "    N = len(coins)\n",
    "    for i, move in enumerate(strategy, 1):\n",
    "        if 'T' not in coins: return coins\n",
    "        coins0 = coins\n",
    "        coins1 = random.choice(list(rotations(coins)))\n",
    "        coins  = flip(coins1, move)\n",
    "        if verbose: \n",
    "            print(f'{i:4d}: {coins0} | rot: {coins1} | flip: {movestr(move, N)} {coins}')\n",
    "    return coins\n",
    "\n",
    "play(coin_search(4), 'HHTH', True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   1: HTTHTTHT | rot: TTHTTHTH | flip: 01234567 HHTHHTHT\n",
      "   2: HHTHHTHT | rot: THHTHTHH | flip: 0 2 4 6  HHHTTTTT\n",
      "   3: HHHTTTTT | rot: HTTTTTHH | flip: 01234567 HHHHHTTT\n",
      "   4: HHHHHTTT | rot: HTTTHHHH | flip: 01  45   HHTHTTTT\n",
      "   5: HHTHTTTT | rot: TTHHTHTT | flip: 01234567 HHHHTTHT\n",
      "   6: HHHHTTHT | rot: THHHHTTH | flip: 0 2 4 6  HHHHTHTT\n",
      "   7: HHHHTHTT | rot: TTHHHHTH | flip: 01234567 HHTTTTHT\n",
      "   8: HHTTTTHT | rot: HTTTTHTH | flip: 012 456  HHTHHTHT\n",
      "   9: HHTHHTHT | rot: THHTHHTH | flip: 01234567 HTHTTHTT\n",
      "  10: HTHTTHTT | rot: HTHTTHTT | flip: 0 2 4 6  HHHTTTTT\n",
      "  11: HHHTTTTT | rot: TTTHHHTT | flip: 01234567 HHHHHTTT\n",
      "  12: HHHHHTTT | rot: HHHHTTTH | flip: 01  45   HHHHTHTT\n",
      "  13: HHHHTHTT | rot: THHHHTHT | flip: 01234567 HHTTTTHT\n",
      "  14: HHTTTTHT | rot: TTHTHHTT | flip: 0 2 4 6  HHTHTTTT\n",
      "  15: HHTHTTTT | rot: TTHHTHTT | flip: 01234567 HHHHTTHT\n",
      "  16: HHHHTTHT | rot: THTHHHHT | flip: 0123     HHHTHTHT\n",
      "  17: HHHTHTHT | rot: HTHTHTHH | flip: 01234567 HTHTHTTT\n",
      "  18: HTHTHTTT | rot: HTHTTTHT | flip: 0 2 4 6  HTTTTTTT\n",
      "  19: HTTTTTTT | rot: THTTTTTT | flip: 01234567 HHHHHHHT\n",
      "  20: HHHHHHHT | rot: HHHTHHHH | flip: 01  45   HHTTHTTT\n",
      "  21: HHTTHTTT | rot: THHTTHTT | flip: 01234567 HHHTTHHT\n",
      "  22: HHHTTHHT | rot: TTHHTHHH | flip: 0 2 4 6  HHHTHHTT\n",
      "  23: HHHTHHTT | rot: HHTTHHHT | flip: 01234567 HHTTTHTT\n",
      "  24: HHTTTHTT | rot: HHTTTHTT | flip: 012 456  HTHTHTTT\n",
      "  25: HTHTHTTT | rot: TTTHTHTH | flip: 01234567 HHHTHTHT\n",
      "  26: HHHTHTHT | rot: HHTHTHTH | flip: 0 2 4 6  HHHHHHHT\n",
      "  27: HHHHHHHT | rot: HHHHHTHH | flip: 01234567 HTTTTTTT\n",
      "  28: HTTTTTTT | rot: TTTTTHTT | flip: 01  45   HHTTHTTT\n",
      "  29: HHTTHTTT | rot: HTTTHHTT | flip: 01234567 HHHTTHHT\n",
      "  30: HHHTTHHT | rot: HTTHHTHH | flip: 0 2 4 6  HHTTTHTT\n",
      "  31: HHTTTHTT | rot: HTTHHTTT | flip: 01234567 HHHTHHTT\n",
      "  32: HHHTHHTT | rot: HHTHHTTH | flip: 01234 6  HHTTHTTT\n",
      "  33: HHTTHTTT | rot: TTHTTTHH | flip: 01234567 HHHTTHHT\n",
      "  34: HHHTTHHT | rot: THHHTTHH | flip: 0 2 4 6  HHHTHHTT\n",
      "  35: HHHTHHTT | rot: THHTTHHH | flip: 01234567 HHTTTHTT\n",
      "  36: HHTTTHTT | rot: THTTHHTT | flip: 01  45   HTTTTTTT\n",
      "  37: HTTTTTTT | rot: TTTTTHTT | flip: 01234567 HHHHHHHT\n",
      "  38: HHHHHHHT | rot: HHHHHHTH | flip: 0 2 4 6  HHHTHTHT\n",
      "  39: HHHTHTHT | rot: HTHTHTHH | flip: 01234567 HTHTHTTT\n",
      "  40: HTHTHTTT | rot: HTHTTTHT | flip: 012 456  HHTTTHTT\n",
      "  41: HHTTTHTT | rot: HHTTTHTT | flip: 01234567 HHHTHHTT\n",
      "  42: HHHTHHTT | rot: THHHTHHT | flip: 0 2 4 6  HHHTTHHT\n",
      "  43: HHHTTHHT | rot: TTHHTHHH | flip: 01234567 HHTTHTTT\n",
      "  44: HHTTHTTT | rot: TTHHTTHT | flip: 01  45   HHHHHHHT\n",
      "  45: HHHHHHHT | rot: HHHHTHHH | flip: 01234567 HTTTTTTT\n",
      "  46: HTTTTTTT | rot: TTHTTTTT | flip: 0 2 4 6  HTHTHTTT\n",
      "  47: HTHTHTTT | rot: THTTTHTH | flip: 01234567 HHHTHTHT\n",
      "  48: HHHTHTHT | rot: HTHTHHHT | flip: 0123     HHHHTTHT\n",
      "  49: HHHHTTHT | rot: TTHTHHHH | flip: 01234567 HHTHTTTT\n",
      "  50: HHTHTTTT | rot: TTHHTHTT | flip: 0 2 4 6  HHHHTHTT\n",
      "  51: HHHHTHTT | rot: HHTHTTHH | flip: 01234567 HHTTTTHT\n",
      "  52: HHTTTTHT | rot: THTHHTTT | flip: 01  45   HTHTTHTT\n",
      "  53: HTHTTHTT | rot: THTTHTTH | flip: 01234567 HHTHHTHT\n",
      "  54: HHTHHTHT | rot: HHTHHTHT | flip: 0 2 4 6  HHHTTTTT\n",
      "  55: HHHTTTTT | rot: TTTTTHHH | flip: 01234567 HHHHHTTT\n",
      "  56: HHHHHTTT | rot: THHHHHTT | flip: 012 456  HTHTTHTT\n",
      "  57: HTHTTHTT | rot: THTHTTHT | flip: 01234567 HHTHHTHT\n",
      "  58: HHTHHTHT | rot: HTHHTHHT | flip: 0 2 4 6  HHHTTTTT\n",
      "  59: HHHTTTTT | rot: HHTTTTTH | flip: 01234567 HHHHHTTT\n",
      "  60: HHHHHTTT | rot: HHHHHTTT | flip: 01  45   HHTHTTTT\n",
      "  61: HHTHTTTT | rot: THTTTTHH | flip: 01234567 HHHHTTHT\n",
      "  62: HHHHTTHT | rot: THTHHHHT | flip: 0 2 4 6  HHHHTHTT\n",
      "  63: HHHHTHTT | rot: HHHTHTTH | flip: 01234567 HHTTTTHT\n",
      "  64: HHTTTTHT | rot: TTTHTHHT | flip: 012345   HHHTHTHT\n",
      "  65: HHHTHTHT | rot: THTHTHHH | flip: 01234567 HTHTHTTT\n",
      "  66: HTHTHTTT | rot: HTHTHTTT | flip: 0 2 4 6  HTTTTTTT\n",
      "  67: HTTTTTTT | rot: TTTTTTTH | flip: 01234567 HHHHHHHT\n",
      "  68: HHHHHHHT | rot: HHHHTHHH | flip: 01  45   HHHTHHTT\n",
      "  69: HHHTHHTT | rot: HHHTHHTT | flip: 01234567 HHTTTHTT\n",
      "  70: HHTTTHTT | rot: TTHHTTTH | flip: 0 2 4 6  HHHTTHHT\n",
      "  71: HHHTTHHT | rot: HTHHHTTH | flip: 01234567 HHTTHTTT\n",
      "  72: HHTTHTTT | rot: THTTTHHT | flip: 012 456  HTHTHTTT\n",
      "  73: HTHTHTTT | rot: TTHTHTHT | flip: 01234567 HHHTHTHT\n",
      "  74: HHHTHTHT | rot: THHHTHTH | flip: 0 2 4 6  HHHHHHHT\n",
      "  75: HHHHHHHT | rot: HHHTHHHH | flip: 01234567 HTTTTTTT\n",
      "  76: HTTTTTTT | rot: TTTTTHTT | flip: 01  45   HHTTHTTT\n",
      "  77: HHTTHTTT | rot: HHTTHTTT | flip: 01234567 HHHTTHHT\n",
      "  78: HHHTTHHT | rot: TTHHTHHH | flip: 0 2 4 6  HHHTHHTT\n",
      "  79: HHHTHHTT | rot: HHTHHTTH | flip: 01234567 HHTTTHTT\n",
      "  80: HHTTTHTT | rot: THTTHHTT | flip: 0123     HHHHTTHT\n",
      "  81: HHHHTTHT | rot: TTHTHHHH | flip: 01234567 HHTHTTTT\n",
      "  82: HHTHTTTT | rot: HTTTTHHT | flip: 0 2 4 6  HHTTTTHT\n",
      "  83: HHTTTTHT | rot: HTHHTTTT | flip: 01234567 HHHHTHTT\n",
      "  84: HHHHTHTT | rot: HHHHTHTT | flip: 01  45   HHHTTTTT\n",
      "  85: HHHTTTTT | rot: THHHTTTT | flip: 01234567 HHHHHTTT\n",
      "  86: HHHHHTTT | rot: HHHHHTTT | flip: 0 2 4 6  HTHTTHTT\n",
      "  87: HTHTTHTT | rot: TTHTTHTH | flip: 01234567 HHTHHTHT\n",
      "  88: HHTHHTHT | rot: THHTHTHH | flip: 012 456  HHTTTTHT\n",
      "  89: HHTTTTHT | rot: THHTTTTH | flip: 01234567 HHHHTHTT\n",
      "  90: HHHHTHTT | rot: HHTHTTHH | flip: 0 2 4 6  HHHHTTHT\n",
      "  91: HHHHTTHT | rot: HTTHTHHH | flip: 01234567 HHTHTTTT\n",
      "  92: HHTHTTTT | rot: HTTTTHHT | flip: 01  45   HTHTTHTT\n",
      "  93: HTHTTHTT | rot: THTTHTHT | flip: 01234567 HHTHHTHT\n",
      "  94: HHTHHTHT | rot: HTHTHHTH | flip: 0 2 4 6  HHHTTTTT\n",
      "  95: HHHTTTTT | rot: TTHHHTTT | flip: 01234567 HHHHHTTT\n",
      "  96: HHHHHTTT | rot: HHTTTHHH | flip: 01234 6  HHHHTHTT\n",
      "  97: HHHHTHTT | rot: TTHHHHTH | flip: 01234567 HHTTTTHT\n",
      "  98: HHTTTTHT | rot: TTHTHHTT | flip: 0 2 4 6  HHTHTTTT\n",
      "  99: HHTHTTTT | rot: TTTHHTHT | flip: 01234567 HHHHTTHT\n",
      " 100: HHHHTTHT | rot: HHTTHTHH | flip: 01  45   HHHTTTTT\n",
      " 101: HHHTTTTT | rot: HHTTTTTH | flip: 01234567 HHHHHTTT\n",
      " 102: HHHHHTTT | rot: HHHHTTTH | flip: 0 2 4 6  HHTHHTHT\n",
      " 103: HHTHHTHT | rot: HTHHTHHT | flip: 01234567 HTHTTHTT\n",
      " 104: HTHTTHTT | rot: HTTHTTHT | flip: 012 456  HHHHHTTT\n",
      " 105: HHHHHTTT | rot: TTHHHHHT | flip: 01234567 HHHTTTTT\n",
      " 106: HHHTTTTT | rot: HHTTTTTH | flip: 0 2 4 6  HHTHHTHT\n",
      " 107: HHTHHTHT | rot: THHTHHTH | flip: 01234567 HTHTTHTT\n",
      " 108: HTHTTHTT | rot: THTTHTTH | flip: 01  45   HHTTTTHT\n",
      " 109: HHTTTTHT | rot: HTTTTHTH | flip: 01234567 HHHHTHTT\n",
      " 110: HHHHTHTT | rot: TTHHHHTH | flip: 0 2 4 6  HHHHTTHT\n",
      " 111: HHHHTTHT | rot: THHHHTTH | flip: 01234567 HHTHTTTT\n",
      " 112: HHTHTTTT | rot: HTTTTHHT | flip: 0123     HHHTHHTT\n",
      " 113: HHHTHHTT | rot: HHTTHHHT | flip: 01234567 HHTTTHTT\n",
      " 114: HHTTTHTT | rot: TTHHTTTH | flip: 0 2 4 6  HHHTTHHT\n",
      " 115: HHHTTHHT | rot: HHHTTHHT | flip: 01234567 HHTTHTTT\n",
      " 116: HHTTHTTT | rot: THHTTHTT | flip: 01  45   HTHTHTTT\n",
      " 117: HTHTHTTT | rot: TTTHTHTH | flip: 01234567 HHHTHTHT\n",
      " 118: HHHTHTHT | rot: THTHTHHH | flip: 0 2 4 6  HHHHHHHT\n",
      " 119: HHHHHHHT | rot: HHHHTHHH | flip: 01234567 HTTTTTTT\n",
      " 120: HTTTTTTT | rot: TTHTTTTT | flip: 012 456  HHHTHHTT\n",
      " 121: HHHTHHTT | rot: HTHHTTHH | flip: 01234567 HHTTTHTT\n",
      " 122: HHTTTHTT | rot: TTHHTTTH | flip: 0 2 4 6  HHHTTHHT\n",
      " 123: HHHTTHHT | rot: THHHTTHH | flip: 01234567 HHTTHTTT\n",
      " 124: HHTTHTTT | rot: TTTHHTTH | flip: 01  45   HHHTHTHT\n",
      " 125: HHHTHTHT | rot: HHTHTHTH | flip: 01234567 HTHTHTTT\n",
      " 126: HTHTHTTT | rot: TTTHTHTH | flip: 0 2 4 6  HHHHHHHT\n",
      " 127: HHHHHHHT | rot: HTHHHHHH | flip: 01234567 HTTTTTTT\n",
      " 128: HTTTTTTT | rot: THTTTTTT | flip: 0123456  HHHHHTHT\n",
      " 129: HHHHHTHT | rot: HHHHHTHT | flip: 01234567 HTHTTTTT\n",
      " 130: HTHTTTTT | rot: TTTHTHTT | flip: 0 2 4 6  HHHHHTHT\n",
      " 131: HHHHHTHT | rot: HTHHHHHT | flip: 01234567 HTHTTTTT\n",
      " 132: HTHTTTTT | rot: TTTHTHTT | flip: 01  45   HHTHHTTT\n",
      " 133: HHTHHTTT | rot: THHTTTHH | flip: 01234567 HHHTTHTT\n",
      " 134: HHHTTHTT | rot: HHHTTHTT | flip: 0 2 4 6  HHHTTHTT\n",
      " 135: HHHTTHTT | rot: THTTHHHT | flip: 01234567 HHTHHTTT\n",
      " 136: HHTHHTTT | rot: HTTTHHTH | flip: 012 456  HHTHHTTT\n",
      " 137: HHTHHTTT | rot: HHTTTHHT | flip: 01234567 HHHTTHTT\n",
      " 138: HHHTTHTT | rot: TTHTTHHH | flip: 0 2 4 6  HHTHHTTT\n",
      " 139: HHTHHTTT | rot: TTHHTHHT | flip: 01234567 HHHTTHTT\n",
      " 140: HHHTTHTT | rot: HHHTTHTT | flip: 01  45   HTHTTTTT\n",
      " 141: HTHTTTTT | rot: TTTHTHTT | flip: 01234567 HHHHHTHT\n",
      " 142: HHHHHTHT | rot: HHTHTHHH | flip: 0 2 4 6  HHHHHTHT\n",
      " 143: HHHHHTHT | rot: HHHHTHTH | flip: 01234567 HTHTTTTT\n",
      " 144: HTHTTTTT | rot: TTHTHTTT | flip: 0123     HHTHHTTT\n",
      " 145: HHTHHTTT | rot: TTHHTHHT | flip: 01234567 HHHTTHTT\n",
      " 146: HHHTTHTT | rot: HTTHHHTT | flip: 0 2 4 6  HHTHHTTT\n",
      " 147: HHTHHTTT | rot: TTTHHTHH | flip: 01234567 HHHTTHTT\n",
      " 148: HHHTTHTT | rot: HHHTTHTT | flip: 01  45   HTHTTTTT\n",
      " 149: HTHTTTTT | rot: THTTTTTH | flip: 01234567 HHHHHTHT\n",
      " 150: HHHHHTHT | rot: THHHHHTH | flip: 0 2 4 6  HHHHHTHT\n",
      " 151: HHHHHTHT | rot: HHHTHTHH | flip: 01234567 HTHTTTTT\n",
      " 152: HTHTTTTT | rot: HTHTTTTT | flip: 012 456  HHHTTHTT\n",
      " 153: HHHTTHTT | rot: HHHTTHTT | flip: 01234567 HHTHHTTT\n",
      " 154: HHTHHTTT | rot: TTTHHTHH | flip: 0 2 4 6  HHTHHTTT\n",
      " 155: HHTHHTTT | rot: THHTTTHH | flip: 01234567 HHHTTHTT\n",
      " 156: HHHTTHTT | rot: TTHHHTTH | flip: 01  45   HHHHHTHT\n",
      " 157: HHHHHTHT | rot: THTHHHHH | flip: 01234567 HTHTTTTT\n",
      " 158: HTHTTTTT | rot: TTHTHTTT | flip: 0 2 4 6  HTHTTTTT\n",
      " 159: HTHTTTTT | rot: THTTTTTH | flip: 01234567 HHHHHTHT\n",
      " 160: HHHHHTHT | rot: THTHHHHH | flip: 01234 6  HHTHTTHT\n",
      " 161: HHTHTTHT | rot: TTHTHHTH | flip: 01234567 HHTHTTHT\n",
      " 162: HHTHTTHT | rot: THTTHTHH | flip: 0 2 4 6  HHHHTTTT\n",
      " 163: HHHHTTTT | rot: THHHHTTT | flip: 01234567 HHHHTTTT\n",
      " 164: HHHHTTTT | rot: HHHTTTTH | flip: 01  45   HHTHTTHT\n",
      " 165: HHTHTTHT | rot: HHTHTTHT | flip: 01234567 HHTHTTHT\n",
      " 166: HHTHTTHT | rot: TTHTHHTH | flip: 0 2 4 6  HHHHTTTT\n",
      " 167: HHHHTTTT | rot: TTTHHHHT | flip: 01234567 HHHHTTTT\n",
      " 168: HHHHTTTT | rot: HHHHTTTT | flip: 012 456  HHHHTTTT\n",
      " 169: HHHHTTTT | rot: TTHHHHTT | flip: 01234567 HHHHTTTT\n",
      " 170: HHHHTTTT | rot: TTTHHHHT | flip: 0 2 4 6  HHTHTTHT\n",
      " 171: HHTHTTHT | rot: TTHTHHTH | flip: 01234567 HHTHTTHT\n",
      " 172: HHTHTTHT | rot: TTHTHHTH | flip: 01  45   HHHHTTTT\n",
      " 173: HHHHTTTT | rot: HTTTTHHH | flip: 01234567 HHHHTTTT\n",
      " 174: HHHHTTTT | rot: HTTTTHHH | flip: 0 2 4 6  HHTHTTHT\n",
      " 175: HHTHTTHT | rot: THHTHTTH | flip: 01234567 HHTHTTHT\n",
      " 176: HHTHTTHT | rot: TTHTHHTH | flip: 0123     HHHTHHHT\n",
      " 177: HHHTHHHT | rot: HTHHHTHH | flip: 01234567 HTTTHTTT\n",
      " 178: HTTTHTTT | rot: TTTHTTTH | flip: 0 2 4 6  HHHTHHHT\n",
      " 179: HHHTHHHT | rot: HHHTHHHT | flip: 01234567 HTTTHTTT\n",
      " 180: HTTTHTTT | rot: TTHTTTHT | flip: 01  45   HHHTHHHT\n",
      " 181: HHHTHHHT | rot: HHHTHHHT | flip: 01234567 HTTTHTTT\n",
      " 182: HTTTHTTT | rot: THTTTHTT | flip: 0 2 4 6  HHHTHHHT\n",
      " 183: HHHTHHHT | rot: HHTHHHTH | flip: 01234567 HTTTHTTT\n",
      " 184: HTTTHTTT | rot: TTTHTTTH | flip: 012 456  HHHHHHHH\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'HHHHHHHH'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "play(strategy8, 'HTTHTTHT', True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
